package com.philips.util;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

import com.philips.service.AQIService;
import com.philips.service.AirService;

public class ContextListener implements ServletContextListener{

	@Override
	public void contextDestroyed(ServletContextEvent sc) {
		
	}

	@Override
	public void contextInitialized(ServletContextEvent sc) {
		try {
			Common.realPath=sc.getServletContext().getRealPath("/");
			Timer timer=new Timer();
//			timer.schedule(new Airtask(), 0,60*60*1000);
			timer.schedule(new AQITask(), 0,60*60*1000);
		} catch (Exception e) {
			e.printStackTrace();
			Log.info(e.getMessage());
		}
	}
}

class AQITask extends TimerTask{
	public void run() {
//		AQIService aqiService=new AQIService();
		AQIService.exportAQI("shanghai");
	};
}

class Airtask extends TimerTask{
	@Override
	public void run() {
		String msg ="";
		try {
			
		AirService as=new AirService();
		String urlaqi = "http://ixuanwu.com.cn/book/AQI/citys.php";
		HttpClient client = new HttpClient();
		
//		连接超时
		client.getHttpConnectionManager().getParams().setConnectionTimeout(60000);  
//		读取超时
		client.getHttpConnectionManager().getParams().setSoTimeout(60000);
		
		GetMethod getaqi = new GetMethod(urlaqi);
		getaqi.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");// 在头文件中设置转码
		client.executeMethod(getaqi);
		String airjson = new String(getaqi.getResponseBodyAsString().getBytes("utf-8"));
//     test data
//			String airjson =AirService.readFile("C:/workspace/air/WebContent/data/json files/");
			msg= as.saveAir(airjson,"shanghai");
			Log.info(msg);
		} catch (Exception e) {
			e.printStackTrace();
			Log.info(e.getMessage());
		}
	}
	
}
